<template>
  <tn-popup
    v-model="showPopup"
    mode="bottom"
    :safe-area-inset-bottom="false"
    :mask="mask"
    :z-index="zIndex"
    :content-custom-style="customPopupContentStyle"
    close-icon=""
    @close="handlePopupClose"
  >
    <view class="tn-picker tn-safe-area-inset-bottom">
      <!-- 头部 -->
      <view class="tn-picker__header">
        <!-- 取消按钮 -->
        <view
          class="cancel"
          :class="[cancelClass]"
          :style="cancelStyle"
          @tap.stop="handleCancelEvent"
        >{{ cancelText }}</view>
        <!-- 头部内容 -->
        <view class="content">
          <slot name="header"></slot>
        </view>
        <!-- 确认按钮 -->
        <view
          class="confirm"
          :class="[confirmClass]"
          :style="confirmStyle"
          @tap="handleConfirmEvent"
        >{{ confirmText }}</view>
      </view>

      <!-- picker内容选择区 -->
      <view class="tn-picker__content">
        <!-- time模式 -->
        <picker-view
          v-if="mode === 'time'"
          class="tn-picker__picker-view"
          :value="timeSelectValue"
          @change="handlePickerChange"
          @pickstart="handlePickerStart"
          @pickend="handlePickerEnd"
        >
          <picker-view-column
            v-for="(item, index) in timeColumnData"
            :key="index"
            class="tn-picker__picker-view-column"
          >
            <view
              v-for="(sub_item, sub_index) in item.value"
              :key="sub_index"
              class="tn-picker__content__item"
            >
              <view class="tn-picker__label tn-text-ellipsis-1">
                {{ subNumber(sub_item, 4) }}<text v-if="timeOption.unit">{{ item.unit }}</text>
              </view>
            </view>
          </picker-view-column>
        </picker-view>
        
        <!-- region模式 -->
        <!-- time模式 -->
        <picker-view
          v-if="mode === 'region'"
          class="tn-picker__picker-view"
          :value="regionSelectValue"
          @change="handlePickerChange"
          @pickstart="handlePickerStart"
          @pickend="handlePickerEnd"
        >
          <picker-view-column
            v-for="(item, index) in regionColumnData"
            :key="index"
            class="tn-picker__picker-view-column"
          >
            <view
              v-for="(sub_item, sub_index) in item"
              :key="sub_index"
              class="tn-picker__content__item"
            >
              <view class="tn-picker__label tn-text-ellipsis-1">
                {{ sub_item }}
              </view>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
  </tn-popup>
</template>

<script lang="ts" setup>
import { 
  pickerProps, 
  pickerEmits, 
  PickerTimeOptions, 
  PickerRegionOptions, 
  PickerTimeResult, 
  PickerRegionResult 
} from '../../../types/tn-picker'
import { computed, CSSProperties, onMounted, ref, watch } from 'vue'
import { ColorInfo } from '../../../types/tuniao-ui'
import useComponentColor from '../../../libs/hooks/useComponentColor'
import useTime from '../lib/hooks/useTime'
import useRegion from '../lib/hooks/useRegion'
import { subNumber } from '../../../utils'
import { UPDATE_MODEL_EVENT } from '../../../constants'
import TnPopup from '../../tn-popup/src/Popup.vue'

const props = defineProps(pickerProps)
const emits = defineEmits(pickerEmits)

// 解析颜色
const { splitColorInfo } = useComponentColor()
// 解析取消文本颜色
const cancelColor = computed<ColorInfo>(() => {
  return splitColorInfo('color', props?.cancelColor)
})
// 解析确认文本颜色
const confirmColor = computed<ColorInfo>(() => {
  return splitColorInfo('color', props?.confirmColor)
})

// 取消按钮样式
const cancelStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (cancelColor.value.type === 'style') style.color = cancelColor.value.value
  return style
})
// 确认按钮样式
const confirmStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (confirmColor.value.type === 'style') style.color = confirmColor.value.value
  return style
})

// 取消按钮对应类
const cancelClass = computed<string>(() => {
  let clazz: string[] = []
  if (cancelColor.value.type === 'class') clazz.push(cancelColor.value.value)
  return clazz.join(' ')
})
// 确认按钮对应类
const confirmClass = computed<string>(() => {
  let clazz: string[] = []
  if (confirmColor.value.type === 'class') clazz.push(confirmColor.value.value)
  return clazz.join(' ')
})

// popup显示
let showPopup = ref<boolean>(false)
watch(() => props.modelValue, (val: boolean) => {
  showPopup.value = val
},{
  immediate: true
})
// popup自定义内容样式
const customPopupContentStyle = ref<CSSProperties>({
  backgroundColor: 'transparent'
})


// time配置项
const timeOption = computed<PickerTimeOptions>(() => {
  const date: Date = new Date()
  const currentYear: number = date.getFullYear()
  // 开始年份
  const startYear: number = currentYear - 5
  // 结束年份
  const endYear: number = currentYear + 5

  return Object.assign({
    year: true,
    month: true,
    day: true,
    hour: false,
    minute: false,
    second: false,
    unit: true,
    startYear,
    endYear,
    timestamp: true
  }, props?.timeOption || {})
})
// region配置项
const regionOption = computed<PickerRegionOptions>(() => {
  return Object.assign({
    province: true,
    city: true,
    area: true
  }, props?.regionOption || {})
})

// 标记是否正在滑动
let moving = ref<boolean>(true)
// 时间选项操作
const { timeColumnData, timeSelectValue, updateTime, updateTimeOption, updateTimeSelectValue, getTimeResult } = useTime()
// 地区选项操作
const { regionColumnData, regionSelectValue, updateRegion, updateRegionOption, updateRegionSelectValue, getRegionResult } = useRegion()

// 初始化数据
const initData = () => {
  if (props.mode === 'time') {
    // 更新配置信息
    updateTimeOption(timeOption.value)
    // 更新默认时间
    let date = new Date()
    if (typeof props?.defaultValue === 'string') {
      let formateDate = props.defaultValue.replace(/\-/g, '/')
      formateDate = 
        formateDate && formateDate.indexOf('/') == -1 
        ? `${date.getFullYear()}/${subNumber(date.getMonth() + 1)}/${subNumber(date.getDate())} ${formateDate}` 
        : formateDate
      if (formateDate) date = new Date(formateDate)
    }
    updateTime(date)
  } else if(props.mode === 'region') {
    // 更新配置信息
    updateRegionOption(regionOption.value)
    // 更新默认地区
    let defaultRegion: string[] = []
    if (Array.isArray(props?.defaultValue)) {
      defaultRegion = (props.defaultValue as string[])
    }
    updateRegion(defaultRegion)
  }
}
watch(() => {
  return [props.mode, props.timeOption, props.regionOption]
}, () => {
  initData()
})

// 开始滚动事件
const handlePickerStart = () => {
  // #ifdef MP-WEIXIN
  moving.value = true
  // #endif
}
// 结束滚动事件
const handlePickerEnd = () => {
  // #ifdef MP-WEIXIN
  moving.value = false
  // #endif
}
// 滚动选择事件
const handlePickerChange = (e: any) => {
  const value: number[] = e.detail.value
  if (props.mode === 'time') {
    updateTimeSelectValue(value)
  } else if (props.mode === 'region') {
    updateRegionSelectValue(value)
  }
}

// 取消事件
const handleCancelEvent = () => {
  emits('cancel')
  handlePopupClose()
}
// 确认事件
const handleConfirmEvent = () => {
  /* #ifdef MP-WEIXIN */
  // 正在滑动不返回
  if (moving.value) return
  /* #endif */
  let result: PickerTimeResult | PickerRegionResult = {}
  if (props.mode === 'time') {
    result = getTimeResult()
  } else if(props.mode === 'region') {
    result = getRegionResult()
  }
  emits('confirm', result)
  handlePopupClose()
}

// popup关闭事件
const handlePopupClose = () => {
  emits(UPDATE_MODEL_EVENT, false)
}

onMounted(() => {
  initData()
})
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
@import '../../../theme.scss';

.tn-picker {
  width: 100%;
  position: relative;
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0rpx 0rpx;

  &__header {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #E6E6E6;

    .cancel,.confirm {
      width: 20%;
    }
    .cancel {
      padding-left: 20rpx;
      color: map-get(map-get($tn-type-color-map, 'danger'), 'normal');
    }
    .confirm {
      padding-right: 20rpx;
      text-align: right;
      color: map-get(map-get($tn-type-color-map, 'success'), 'normal');
    }
    .content {
      flex: 1;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &__content {
    width: 100%;
    height: 500rpx;
    &__item {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
  }
  &__picker-view {
    height: 100%;
  }
  &__picker-view-column {
    width: 100%;
  }
}
</style>
